from odoo.http import request, Response
from odoo import http, Command
from odoo.addons.api_manager.tools.check_token import check_token
from odoo.addons.api_manager.tools.create_records import create_records
import logging
import json
from odoo import fields, _
from odoo.exceptions import ValidationError
import datetime
from collections import defaultdict
_logger = logging.getLogger(__name__)


class ApiPurchaseWarehouse(http.Controller):

    @http.route("/v1.0/sb_api/wms/purchase", auth='public', type='http', methods=['post'], csrf=False)
    @check_token
    def wms_api_in_warehouse(self, **kwargs):
        """采购入库， 每天凌晨wms同步入库信息
        """
        _logger.info('WMS采购接收入库...')
        request.env.uid = 2
        data = request.httprequest.get_json()
        result = {
            'json': True,
            'data': {}
        }
        api_result = {
            'code': 0,
            'message': 'success'
        }
        try:
            params = data.get('params')
            # pickingname-采购单id
            order_name = data.get('order_name').split('-')[0]
            po_id = int(data.get('order_name').split('-')[1])
            # 采购入库单或欠单
            picking = request.env['stock.picking'].search(['|', ('purchase_id', '=', int(po_id)), ('name', '=', order_name)]).filtered(lambda x: x.state not in ['cancel', 'done'])
            if not picking:
                raise ValidationError('采购入库单号错误: {}'.format(order_name))
            move_dict = {}
            for param in params:
                product_code = param.get('product_code')
                move = picking.move_ids.filtered(lambda x: x.product_code==product_code)
                location_barcode = param.get('location_barcode')
                if not location_barcode:
                    raise ValidationError('库位编码不能为空')
                location_id = request.env['stock.location'].search([('barcode', '=', location_barcode)], limit=1)
                if not move:
                    raise ValidationError(
                       '未查询到需要入库的采购入库明细行：{}, {}'.format(order_name, param.get('po_line')))
                if not location_id:
                    raise ValidationError('未查询到入库库位: {}'.format(location_barcode))

                qty = param.get('qty')
                production_date = param.get('production_date')
                lot_name = param.get('lot_name')
                datetime_object = datetime.datetime.strptime(production_date, "%Y-%m-%d")
                if move in move_dict.keys():
                    # move_dict[move]['production_date'] = datetime_object
                    move_dict[move]['move_line_ids'].append((0, 0, {
                        'location_dest_id': location_id.id,
                        'quantity': qty,
                        'product_uom_id': move.product_uom.id,
                        'date': fields.Datetime.now(),
                        'reference': move.name,
                        'lot_name': lot_name,
                        'product_id': move.product_id.id
                    }))
                else:
                    move_dict[move] = {
                        'production_date': datetime_object,
                        'move_line_ids': [
                            (0, 0, {
                                'location_dest_id': location_id.id,
                                'quantity': qty,
                                'product_uom_id': move.product_uom.id,
                                'date': fields.Datetime.now(),
                                'reference': move.name,
                                'lot_name': lot_name,
                                'product_id': move.product_id.id
                            })
                        ]
                    }
                move.move_line_ids = [Command.clear()]
                # move_line_ids = [(0, 0, {
                #     'location_dest_id': location_id.id,
                #     'quantity': qty,
                #     'product_uom_id': move.product_uom.id,
                #     'date': fields.Datetime.now(),
                #     'reference': move.name,
                #     'lot_name': lot_name,
                #     'product_id': move.product_id.id
                # })]
                # move.update({
                #     'production_date': datetime_object,
                #     'move_line_ids': move_line_ids
                # })
            picking.message_post(body=str(move_dict))
            for m, v in move_dict.items():
                # m = request.env['stock.move'].browse([m_id])
                m.update(v)
            if picking.sb_required_iqc:
                picking.action_message()
                picking.check_ids.write({'s_from_wms': True})
            else:
                res = picking.button_validate()
                # 创建欠单
                if type(res) == dict and res.get('res_model', '') == 'stock.backorder.confirmation':
                    confirmation = request.env['stock.backorder.confirmation'].with_context(
                        button_validate_picking_ids=[picking.id]).create({
                        'pick_ids': [(4, picking.id)]
                    })
                    confirmation.process()
        except Exception as e:
            api_result['message'] = '{}'.format(e)
            api_result['code'] = -1
            request.env.cr.rollback()
        result['data'] = api_result
        result_json = json.dumps(result, ensure_ascii=False)
        create_records(result_json)
        return Response(result_json)
